package cn.codergege.demo.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Profile("production")
@Configuration
@PropertySource("classpath:/production/db.properties")
public class ProdDataSourceConfig implements DataSourceConfig {

    @Autowired
    private Environment env;

    private String getEnvProperty(String propertyName) {
        return env.getProperty(propertyName);
    }

    private int getIntEnvProperty(String propertyName) {
        return Integer.parseInt(env.getProperty(propertyName));
    }

    @Override
    @Bean
    public DataSource createDataSource() {
        System.out.println("----> production: dataSource ");
        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass(getEnvProperty("jdbc.driver"));
            ds.setJdbcUrl(getEnvProperty("jdbc.url"));
            ds.setUser(getEnvProperty("jdbc.username"));
            ds.setPassword(getEnvProperty("jdbc.password"));

            ds.setInitialPoolSize(getIntEnvProperty("initialSize"));
            ds.setMaxPoolSize(getIntEnvProperty("maxSize"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }

        return ds;
    }
}
			
			